clear all
set more off

clear all

local alpha = `1'
local beta = `2'
local sigma = `3'
local sigmax = `4'
local J = `5'
local N = `6'
local dgp = `7'
local K=`8'


set obs `N'




if(`dgp' == 1) {
 gen c = exp(-2+1.5*rnormal())

}

if(`dgp' == 2) {
*Now c is the threshold utility at which you stop searching
 gen c = exp(-0.35+1.5*rnormal())
}

if(`dgp' == 3) {
*Now you search if free utility > c
 gen c = -1+4*rnormal()
}

if(`dgp' == 4) {
*Randomly search up to c goods
 gen c = `J'
}

gen alpha = `alpha'
gen beta = `beta'
gen ID = _n

do programs/makedatasetup.do `J' `sigma' `sigmax'  





if(`dgp' == 1) {
do programs/makesimsetup.do `J' `sigma' `sigmax' `K'
}

if(`dgp' == 2) {
do programs/makesimsetupsatisfice.do `J' `sigma' `sigmax' `K'
}

if(`dgp' == 3) {
do programs/makesimsetupthreshold.do `J' `sigma' `sigmax' `K'
}

if(`dgp' == 4) {
do programs/makesimsetuprandomstop.do `J' `sigma' `sigmax' `K'
}





replace z=-1e20 if altID==0
bys ID: egen maxz = max(z)
gen ismax = (maxz == z)


local Jminus = `J'-1

gen maxID = altID if ismax == 1
bys ID: egen maxmaxID = max(maxID)
drop maxID
rename maxmaxID maxID

replace open=0 if xout==1
sum open if z == maxz
local openmax=r(mean)
sum open 
local openall=r(mean)*`J'

replace z=0 if altID==0


*record outside option nonsearch shares
gen chosenout=(chosen==1&xout==1)
bys ID:egen sumout=sum(chosenout)
sum sumout 
local outshare=r(mean)
bys ID:egen sumopen=sum(open)
gen outnosearch=(chosen==1&xout==1&sumopen==0)
bys ID:egen sumoutnosearch=sum(outnosearch)
sum sumoutnosearch
local outnosearchshare=r(mean)
drop chosenout sumout sumopen outnosearch sumoutnosearch



*record alpha 
*limited z variation method 
preserve 
bysort ID:egen stdz=sd(z)
keep ID stdz
duplicates drop
xtile zdecile=stdz,nq(10)
tempfile zdecile 
save `zdecile',replace
restore 

merge m:1 ID using `zdecile'
drop _merge

preserve
 keep if zdecile==1 
 clogit chosen x xout z ,group(ID) 
 local alpha = _b[x]
restore

drop zdecile


keep if _n == 1
keep chosen
gen dgp = `dgp'
gen J = `J'
gen alpha=`alpha'
gen outnosearchshare=`outnosearchshare'
gen K=`K'

drop chosen


